var express = require('express'),
    sio = require('socket.io'),
    model = require('./public/scripts/game'),
    utils = require('./public/scripts/utils.js');

var app = express.createServer();

app.configure(function () {
	app.use(express.static(__dirname + '/public'));
	app.set("views", __dirname + '/views');
	app.set("view options", { layout: false });
});

var io = sio.listen(app);

    io.set('transports', [
        //'websocket',
        'flashsocket',
        'htmlfile',
        'xhr-polling',
        'jsonp-polling'
    ]);

var HOST = process.env.speedSweeperHost || 'http://localhost';
var PORT = process.env.VCAP_APP_PORT || process.env.speedSweeperPort || 8080;
var WEB_SOCKET_INCOMING_PORT = process.env.speedSweeperWebSocketIncomingPort || 8080;

app.listen(PORT);

io.sockets.on('connection', function (socket) {
	
	socket.on('startGame', function (width, height) {
		
		var player = createPlayer(socket);
		var game = new model.Game(player, width, height, utils.createMineFieldDesigner());
		socket.on('touch', function (coord) {
			game.touch(coord);
		});
		socket.on('slam', function (coord) {
			game.slam(coord);
		});
		socket.on('flag', function (coord) {
			game.flag(coord);
		});
	});

});


app.get('/', function(req, res){
	res.render('welcome.jade');
});

app.get('/online', function(req, res){
	res.render('game.jade', {scripts: ['/socket.io/socket.io.js','scripts/serverSideBridge.js'], serverURL:HOST +':'+WEB_SOCKET_INCOMING_PORT});
});

app.get('/offline', function(req, res){
	res.render('game.jade', {scripts: ['scripts/game.js','scripts/clientSideBridge.js']});
});

function createPlayer(socket){
	return {
		win : function (message) {
			socket.emit('win', message);
		},
		lose : function (gameJson) {
			this.update(gameJson);
			socket.emit('lose');	
		},
		update : function (gameJson) {
			socket.emit('update', gameJson);
		},
		error : function(message){ 
			socket.emit("error", message);
		}
	}
}

